package linearstructure.linkedlist.doublelist;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-05-25 17:30
 * @ Description : 双向链表
 */
public class DoubleLinkedList
{
    private Node head = new Node(0, "", "");

    public Node getHead()
    {
        return head;
    }

    //遍历
    public void list()
    {
        if (head.next == null)
        {
            System.out.println("链表为空");
            return;
        }
        Node temp = head.next;
        while (temp != null)
        {
            System.out.println(temp);
            temp = temp.next;
        }
    }

    //添加(尾插法)
    public void add(Node node)
    {
        Node temp = head;
        while (temp.next != null)
        {
            temp = temp.next;
        }
        temp.next = node;
        node.pre = temp;
    }

    //修改
    public void update(Node newNode)
    {
        if (head.next == null)
        {
            System.out.println("链表为空");
            return;
        }
        Node temp = head.next;
        boolean flag = false;//表示是否找到该节点
        while (true)
        {
            if (temp == null)
            {
                //找到最后一个
                break;
            }
            if (temp.no == newNode.no)
            {
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if (flag)
        {
            temp.name = newNode.name;
            temp.nickname = newNode.nickname;
        }
        else
        {
            System.out.printf("没有找到编号为%d的节点", newNode.no);
        }
    }

    //删除
    public void delete(int no)
    {
        if (head.next == null)
        {
            System.out.println("链表为空");
            return;
        }
        Node temp = head.next;
        boolean flag = false;
        while (true)
        {
            if (temp == null)
            {
                break;
            }
            if (temp.no == no)
            {
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if (flag)
        {
            temp.pre.next = temp.next;
            if (temp.next != null)
            {
                temp.next.pre = temp.pre;
            }
        }
        else
        {
            System.out.printf("待删除的节点编号%d不存在", no);
        }

    }


}
